package com.longge;

public class SurfaceArea {

    public int surfaceArea(int[][] grid) {

        int[] dx = new int[]{0, 1, 0, -1};
        int[] dy = new int[]{1, 0, -1, 0};
        int res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] > 0) {
                    res += 2;
                    for (int k = 0; k < 4; k++) {
                        int x = dx[k] + i;
                        int y = dy[k] + j;
                        int h = 0;
                        if (x >= 0 && y >= 0 && x < grid.length && y < grid[0].length) {
                            h = Math.max(0, grid[i][j] - grid[x][y]);
                        } else {
                            h = grid[i][j];
                        }
                        res += h;
                    }
                }
            }
        }
        return res;
    }
}
